<?php

namespace Hi;

class Layout{

    /**
     * 布局变量容器
     * @var
     */
    protected $_container;
    /**
     * 布局文件路径
     * @var
     */
    private $_layoutPath;
    /**
     * 布局名称
     * @var
     */
    protected $_layout;
    /**
     * 实例对象
     * @var
     */
    protected static $_instance;

    /**
     * 获取实例
     * @return Layout
     */
    public static function getInstance() {
        if (self::$_instance === null) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function __set($key, $value) {
        $this->_container[$key] = $value;
    }

    public function __get($key) {
        if (isset($this->_container[$key])) {
            return $this->_container[$key];
        }
        return null;
    }

    /**
     * 设置布局文件所在路径
     * @param $path
     * @return $this
     */
    public function setLayoutPath($path) {
        $this->_layoutPath = (string) $path;

        return $this;
    }

    /**
     * 获取布局文件所在路径
     * @return mixed
     */
    public function getLayoutPath() {
        return $this->_layoutPath;
    }

    public function setLayout($name) {
        if (!preg_match('/^[a-zA-Z][a-zA-Z0-9_]*$/',$name)) {
            throw new Exceptions('Layout "' . $name . '" invalid.');
        }
        $this->_layout = (string) $name;

        return $this;
    }

    /**
     * 获取布局
     * @return mixed
     */
    public function getLayout() {
        return $this->_layout;
    }

    /**
     * 获取布局脚本
     * @return string
     * @throws Exceptions
     */
    public function getLayoutScript() {
        $layoutScript = $this->getLayoutPath() . DS . $this->getLayout() . '.php';
        if (!file_exists($layoutScript)) {
            throw new Exceptions('Layout "' . $this->getLayout() . '" does not exist.');
        }
        return $layoutScript;
    }
}